package com.geovis.emergency.spd.controller.mobile;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.geovis.common.auth.util.AuthUtil;
import com.geovis.common.core.api.Result;
import com.geovis.common.core.controller.BaseController;
import com.geovis.common.mybatis.page.PageParam;
import com.geovis.common.mybatis.page.PageResult;
import com.geovis.emergency.spd.biz.pc.service.IPcMessageService;
import com.geovis.emergency.spd.entity.mobile.pojo.vo.MessageMobileVO;
import com.geovis.emergency.spd.entity.pc.entity.PcMessage;
import com.geovis.emergency.spd.entity.pc.pojo.constant.PcMessageConstant;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.parameters.P;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：linwl
 * @date ：Created in 2022/6/16 16:12
 * @description：移动端消息通知模块
 * @version: v1
 */
@RestController
@RequestMapping("/mobile/pcMessage")
@RequiredArgsConstructor
@Api(value = "移动端-应急预案指挥模块-消息通知相关接口", tags = "移动端-应急预案指挥模块-消息通知相关接口")
@Slf4j
public class PcMessageMobileController extends BaseController<IPcMessageService> {

    private final IPcMessageService pcMessageService;

    @ApiOperation("测试发送消息")
    @GetMapping("sendTestMsg")
    public Result<Void> sendTestMsg(String msg){
        PcMessage pcMessage = new PcMessage();
        pcMessage.setPcDrillId("1529631050455683073");
        pcMessage.setType(PcMessageConstant.TYPE_CUSTOMER);
        pcMessage.setTitle("测试消息");
        pcMessage.setContent(msg);
        pcMessage.setStatus("0");
        pcMessage.setRelatedId("1");
        pcMessage.setSenderId("1303246323650252802");
        pcMessage.setAcceptId("1520307169457614850");
        pcMessage.setIsDeleted("0");
        pcMessageService.sendMobileMessage(pcMessage);
        return Result.ok();
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取用户最新的三条消息", notes = "获取用户最新的三条消息")
    @GetMapping("thirdNew/{drillId}")
    public Result<List<MessageMobileVO>> getThirdNewMessage(@ApiParam(value = "演练id",required = true) @PathVariable String drillId){
        String userId = AuthUtil.getCurrentUserId();
        LambdaQueryWrapper<PcMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(e->e.eq(PcMessage::getAcceptId,userId).or().isNull(PcMessage::getAcceptId));
//        wrapper.eq(PcMessage::getAcceptId,userId);
        wrapper.eq(PcMessage::getPcDrillId,drillId);
        wrapper.orderByAsc(PcMessage::getStatus);
        wrapper.orderByDesc(PcMessage::getCreateTime);
        List<PcMessage> list = baseService.list(wrapper);
        Date today = new Date();
        Date yesterday = DateUtil.yesterday();
        if(list.size()>3){
            list = CollectionUtil.sub(list,0,3);
        }
        return Result.ok(list.stream().map(e -> voWrapper(e, today, yesterday)).collect(Collectors.toList()));
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页获取用户消息",notes = "分页获取用户消息")
    @PostMapping("getUserMessage")
    public Result<PageResult> getUserMessage(@RequestBody @Validated PageParam<PcMessage> pageParam) {
        PageResult pageResult = baseService.listPage(pageParam);
        Date today = new Date();
        Date yesterday = DateUtil.yesterday();
        List records = pageResult.getRecords();
        if(CollectionUtil.isNotEmpty(records)){
            List<PcMessage> pcMessageList = records;
            List<MessageMobileVO> messageMobileVOS = pcMessageList.stream().map(e -> voWrapper(e, today, yesterday)).collect(Collectors.toList());
            String time = "";
            for (MessageMobileVO messageMobileVO : messageMobileVOS) {
                if(StrUtil.isNotBlank(messageMobileVO.getSendTimeTag()) && time.equals(messageMobileVO.getSendTimeTag())){
                    messageMobileVO.setSendTimeTag("");
                }else{
                    time = messageMobileVO.getSendTimeTag();
                }
            }
            pageResult.setRecords(messageMobileVOS);
        }
        return Result.ok(pageResult);
    }

    /**
     * vo转换器
     * @param pcMessage 需要转换的实体类
     * @param today 当前时间
     * @return
     */
    private MessageMobileVO voWrapper(PcMessage pcMessage, Date today,Date yesterday){
        MessageMobileVO vo = new MessageMobileVO();
        vo.setMessageId(pcMessage.getId());
        vo.setTitle(pcMessage.getTitle());
        vo.setContent(pcMessage.getContent());
        vo.setStatus(pcMessage.getStatus());
        Date date = Date.from(pcMessage.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
        //当天
        if(DateUtil.isSameDay (today,date)){
            vo.setSendTimeDynamic(DateUtil.format(date,"HH:mm"));
            vo.setSendTimeTag("");
        }else{
            vo.setSendTimeDynamic(DateUtil.formatDateTime(date));
            //昨天
            if(DateUtil.isSameDay(yesterday,date)){
                vo.setSendTimeTag("昨天");
            }else{
                vo.setSendTimeTag(DateUtil.formatDate(date));
            }
        }
        vo.setSendTime(DateUtil.format(date,"HH:mm"));
        return vo;
    }
}
